<?php


/*  */

$error=false;

// Check if mysql extension is available
if (!$error && !function_exists('mysql_connect'))
{
	echo ("<p class=\"error\">There is no mySQL extension available in your PHP installation. Sorry!</p>\n");
	$error=true;
}

// check for PHP version
if (!$error && version_compare(phpversion(), "5.3.0", ">=")  == 1) {
	error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
}
else {
	error_reporting(E_ALL & ~E_NOTICE);
}


//$error = ! ( !error && isset ($sTerm) && sizeof($sTerm)>0 );

$db_server   = '127.0.0.1';
$db_name     = 'invima';
$db_username = 'root';
$db_password = 'l0rdy4v3h';
$dbconnection = false;

$db_connection_charset = '';

// Connect to the database, set charset and execute pre-queries
if (!$error)
{
	$dbconnection = mysql_connect($db_server,$db_username,$db_password);
	if ($dbconnection)
		$db = @mysql_select_db($db_name);
	if (!$dbconnection || !$db)
	{
		echo ("<p class=\"error\">Database connection failed due to ".mysql_error()."</p>\n");
		echo ("<p>Edit the database settings in ".$_SERVER["SCRIPT_FILENAME"]." or contact your database provider.</p>\n");
		$error=true;
	}
	if (!$error && $db_connection_charset!=='')
		@mysql_query("SET NAMES $db_connection_charset", $dbconnection);
}
else
{
	$dbconnection = false;
}

if ($error) {
	echo "error";
	exit;
}

/* BODY */

function getParamValue( $fieldName ) {
	return ( isset($_POST[$fieldName]) ) ? $_POST[$fieldName] : $_GET[$fieldName];
}


function autocomplete( $sSearchBy, $sValue, $db) {

	$sTerm = strtoupper($sTerm);
	$query = "SELECT DISTINCT (`".$sSearchBy."`) FROM `medicines` WHERE `".$sSearchBy."` LIKE '".$sValue."%' GROUP BY  `".$sSearchBy."`;";
	$data = array();

	if ( !$error )
	{
		$rs = mysql_query($query, $db);

		// loop through each data returned and format the response for jQuery
		if ( $rs && mysql_num_rows($rs) )
		{
			while( $row = mysql_fetch_row($rs) )
			{
				$data[] = $row[0];
			}
		}

	}

	return $data;

}

function preview( $sField, $sValue, $db) {
	
	$query = "SELECT DISTINCT (`".$sField."`) as field, COUNT(`".$sField."`) as count FROM `medicines` WHERE (`Producto` LIKE '".$sValue."%') OR (`PrincipioActivo` LIKE '".$sValue."%') GROUP BY  `".$sField."`;";
	$data = array();
	
	if ( !$error )
	{
		$data['count'] = 0;
		
		$rs = mysql_query($query, $db);
	
		// loop through each data returned and format the response for jQuery
		if ( $rs && mysql_num_rows($rs) )
		{
			$data['values'] = array();
			
			while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
			{
				$data['values'][ $row['field'] ] = $row['count'];
				$data['count'] += $row['count'];
			}
		}
	
	}

	return $data;

}

function doQuery( $sFieldName, $sFieldValue, $aFilters, $iStart, $iLength, $db ) {

	$sTerm = strtoupper($sTerm);
	
	$query = 'SELECT SQL_CALC_FOUND_ROWS * FROM `medicines` WHERE `'.$sFieldName.'` LIKE "'.$sFieldValue.'" ';
	
	foreach( $aFilters as $sField=>$aValues ) {
		$query .= ' AND (`'.$sField.'` IN ("'.implode('","',$aValues).'") )';
	}
	
	if ( $iStart >= 0 && $iLength > 0 ) {
		$query .= ' LIMIT '.$iStart.', '.$iLength;
	}
	
	$data = array();
	$data['aaData'] = array();
	$data['iTotalDisplayRecords'] = 0;
	$data['iTotalRecords'] = 0;

	if ( !$error )
	{
		$rs = mysql_query($query, $db);
		$query_count = mysql_query("SELECT FOUND_ROWS()", $db );
		$count = mysql_fetch_array($query_count);

		$data['iTotalDisplayRecords'] = $count[0]; //($rs)? mysql_num_rows($rs) : 0;
		$data['iTotalRecords'] = $count[0];

		// loop through each data returned and format the response for jQuery
		if ( $rs && mysql_num_rows($rs) )
		{
			while( $row = mysql_fetch_row($rs) )
			{
				$data['aaData'][] = $row;
			}
		}

	}
	
	return $data;

}


/* BODY */

// check for the term
$sQuery = getParamValue('q');
$sType = getParamValue('type');
$sMedicine = getParamValue('producto');
$sCompound = getParamValue('componente');
$sForma = getParamValue('forma');
$sIndicacion = getParamValue('indicacion');
$iStart = getParamValue('start');
$iLength = getParamValue('length');
$sFields =  getParamValue('fields');

$aColumnNames = array(
"Expediente",
"Producto",
"Titular",
"Registro",
"Expedicion",
"Vencimiento",
"Estado",
"Consecutivo",
"Cantidad1",
"Presentacion",
"Estado",
"FechaActivo",
"FechaInactivo",
"Unidad",
"Atc",
"PrincipioActivo",
"Via",
"Concentracion",
"Principio Activo",
"Medida",
"Cantidad",
"Referencia",
"Forma",
"Fabricante",
"Modalidad"
);

$result = array();

switch ( $sType ) {
	
	case "autocomplete": {
		// TODO: SOON
		
		if ( isset($sFields) ) {
			$aFields = explode(";", $sFields);
		}
		
		foreach( $aFields as $sField ) {
			if ( !empty($sField) ) {
				$result[$sField] = autocomplete($sField, $sQuery, $dbconnection );
			}
		}
		
		break;
	}
	
	case "preview": {
		
		$result['Forma Farmaceutica'] = preview( 'Forma', $sQuery, $dbconnection );

		break;
	}
	
	default: {
		
		$aFilters = array();
		
		
		foreach ( $aColumnNames as $sColumnName ) {
			$sColumnValue = getParamValue($sColumnName);
			
			if ( isset($sColumnValue) ) {
				$aFilters[$sColumnName] = explode(";", $sColumnValue);
			}
		}
		
// 		if ( isset($sForma) ) {
// 			$aFilters['Forma'] = explode(";", $sForma);
// 		}
		
// 		if ( isset($sIndicacion) ) {
// 			$aFilters['Indicacion'] = explode(";", $sIndicacion);
// 		}
		
		if ( isset($sMedicine) ) {
			$result = doQuery( 'Producto', $sMedicine, $aFilters, $iStart, $iLength, $dbconnection );
			
		} else {
			$result = doQuery( 'PrincipioActivo', $sCompound, $aFilters, $iStart, $iLength, $dbconnection );
		}
		
	}
}

echo json_encode($result);

?>
